const settingsBtn = document.getElementById('settingsBtn');
settingsBtn.addEventListener('click', showSettingsModal);

// 获取cookie函数
function getCookie(name) {
    const cookies = document.cookie.split('; ');
    for (let cookie of cookies) {
        const [key, value] = cookie.split('=');
        if (key === name) return value;
    }
    return null;
}

function showSettingsModal() {
    // 检查用户是否已登录
    const token = getCookie('token');
    if (!token) {
        alert('请先登录账号');
        return;
    }
    
    fetch('/api/settings', {
        method: 'GET',
        headers: {
            
        }
    })
    .then(response => response.json())
    .then(currentSettings => {
        modalBody.innerHTML = `
            <h2>系统设置</h2>
            <h3>LLM 设置</h3>
            <div class="form-group">
                <label>服务器 IP</label>
                <input type="text" id="llm_server_ip" value="${currentSettings.LLM.SERVER_IP || ''}">
            </div>
            <div class="form-group">
                <label>服务器端口</label>
                <input type="text" id="llm_server_port" value="${currentSettings.LLM.SERVER_PORT || ''}">
            </div>
            <div class="form-group">
                <label>嵌入模型</label>
                <input type="text" id="llm_embedding_model" value="${currentSettings.LLM.EMBEDDING_MODEL || ''}">
            </div>
            <div class="form-group">
                <label>API 接口</label>
                <input type="text" id="llm_api_port" value="${currentSettings.LLM.API_PORT || ''}">
            </div>
            <div class="form-group">
                <label>语言模型名称</label>
                <input type="text" id="llm_model_name" value="${currentSettings.LLM.MODEL_NAME || ''}">
            </div>
            <div class="form-group">
                <label>API Key</label>
                <input type="text" id="llm_api_key" value="${currentSettings.LLM.API_KEY || ''}">
            </div>
            <h3>RAG 设置</h3>
            <div class="form-group">
                <label>persist path</label>
                <input type="text" id="rag_persist_path" value="${currentSettings.RAG.PERSIS_PATH || ''}">
            </div>
            <h3>知识系统</h3>
            <div class="form-group">
                <label>上传文件夹</label>
                <input type="text" id="fs_persist_path" value="${currentSettings.FILE_SYSTEM.UPLOAD_FOLDER || ''}">
            </div>
            <div class="form-group">
                <label>向量数据库</label>
                <input type="text" id="fs_chroma_db" value="${currentSettings.FILE_SYSTEM.CHROMA_DB || ''}">
            </div>
            <div class="form-group">
                <label>jwt密钥</label>
                <input type="text" id="fs_jwt_secret_key" value="${currentSettings.FILE_SYSTEM.JWT_SECRET_KEY || ''}">
            </div>
            <h3>AUDIO 设置</h3>
            <div class="form-group">
                <label>采样率 (Sample Rate)</label>
                <input type="number" id="audio_sample_rate" value="${currentSettings.AUDIO.SAMPLE_RATE || 16000}">
            </div>
            <div class="form-group">
                <label>通道数 (Channels)</label>
                <input type="number" id="audio_channels" value="${currentSettings.AUDIO.CHANNELS || 1}">
            </div>
            <div class="form-group">
                <label>分片大小 (Chunk Size)</label>
                <input type="number" id="audio_chunk_size" value="${currentSettings.AUDIO.CHUNK_SIZE || 4096}">
            </div>
            <div class="form-group">
                <label>静音阈值 (Silence Threshold)</label>
                <input type="number" id="audio_silence_threshold" value="${currentSettings.AUDIO.SILENCE_THRESHOLD || 1200}">
            </div>
            <div class="form-group">
                <label>静音时长 (Silence Duration)</label>
                <input type="number" step="0.1" id="audio_silence_duration" value="${currentSettings.AUDIO.SILENCE_DURATION || 2.0}">
            </div>
            <div class="form-group">
                <label>缓冲时长 (Buffer Duration)</label>
                <input type="number" step="0.1" id="audio_buffer_duration" value="${currentSettings.AUDIO.BUFFER_DURATION || 0.5}">
            </div>
            <div class="form-group">
                <label>音频服务 IP</label>
                <input type="text" id="audio_server_ip" value="${currentSettings.AUDIO.SERVER_IP || ''}">
            </div>
            <div class="form-group">
                <label>音频服务端口</label>
                <input type="number" id="audio_server_port" value="${currentSettings.AUDIO.SERVER_PORT || 12345}">
            </div>
            <div class="form-group">
                <label>唤醒词 (Wake Words)</label>
                <input type="text" id="audio_wake_words" value="${currentSettings.AUDIO.WAKE_WORDS || ''}">
            </div>
            <div class="form-group">
                <label>休眠词 (Sleep Words)</label>
                <input type="text" id="audio_sleep_words" value="${currentSettings.AUDIO.SLEEP_WORDS || ''}">
            </div>
            <h3>FISHSPEECH</h3>
            <div class="form-group">
                <label>DEFAULT_API_TOKEN</label>
                <input type="text" id="default_api_token" value="${currentSettings.FISHSPEECH.DEFAULT_API_TOKEN || ''}">
            </div>
            <div class="form-group">
                <label>DEFAULT_MODEL_ID</label>
                <input type="text" id="default_model_id" value="${currentSettings.FISHSPEECH.DEFAULT_MODEL_ID || ''}">
            </div>
            <div class="form-group">
                <label>DEFAULT_AUDIO_FORMAT</label>
                <input type="text" id="default_audio_format" value="${currentSettings.FISHSPEECH.DEFAULT_AUDIO_FORMAT || ''}">
            </div>
            <div class="form-group">
                <label>DEFAULT_TTS_VERSION</label>
                <input type="text" id="default_tts_version" value="${currentSettings.FISHSPEECH.DEFAULT_TTS_VERSION || ''}">
            </div>
            <div class="form-group">
                <label>FISH_SPEECH_URL</label>
                <input type="text" id="default_speech_url" value="${currentSettings.FISHSPEECH.FISH_SPEECH_URL || ''}">
            </div>
            <h3>远端同步</h3>
            <div class="form-group">
                <label>网络地址</label>
                <input type="text" id="sync_server_ip" value="${currentSettings.SYNCSERVER.SERVER_IP || ''}">
            </div>
            <div class="form-group">
                <label>端口</label>
                <input type="text" id="sync_server_port" value="${currentSettings.SYNCSERVER.SERVER_PORT || ''}">
            </div>
            <button id="saveSettings">保存设置</button>
            `;

        modal.style.display = 'block';
        document.getElementById('saveSettings').addEventListener('click', saveSettings);
    })
    .catch(error => console.error('加载设置失败:', error));
}

function saveSettings() {
    const llm_server_ip = document.getElementById('llm_server_ip').value;
    const llm_server_port = document.getElementById('llm_server_port').value;
    const llm_embedding_model = document.getElementById('llm_embedding_model').value;
    const llm_api_port = document.getElementById('llm_api_port').value;
    const llm_model_name = document.getElementById('llm_model_name').value;
    const llm_api_key = document.getElementById('llm_api_key').value;
    const rag_persist_path = document.getElementById('rag_persist_path').value;
    const fs_persist_path = document.getElementById('fs_persist_path').value;
    const fs_chroma_db = document.getElementById('fs_chroma_db').value;
    const fs_jwt_secret_key = document.getElementById('fs_jwt_secret_key').value;
    const audio_sample_rate = document.getElementById('audio_sample_rate').value;
    const audio_channels = document.getElementById('audio_channels').value;
    const audio_chunk_size = document.getElementById('audio_chunk_size').value;
    const audio_silence_threshold = document.getElementById('audio_silence_threshold').value;
    const audio_silence_duration = document.getElementById('audio_silence_duration').value;
    const audio_buffer_duration = document.getElementById('audio_buffer_duration').value;
    const audio_server_ip = document.getElementById('audio_server_ip').value;
    const audio_server_port = document.getElementById('audio_server_port').value;
    const audio_wake_words = document.getElementById('audio_wake_words').value;
    const audio_sleep_words = document.getElementById('audio_sleep_words').value;
    const default_api_token = document.getElementById('default_api_token').value;
    const default_model_id = document.getElementById('default_model_id').value;
    const default_audio_format = document.getElementById('default_audio_format').value;
    const default_tts_version = document.getElementById('default_tts_version').value;
    const default_speech_url = document.getElementById('default_speech_url').value;
    const sync_server_ip = document.getElementById('sync_server_ip').value;
    const sync_server_port = document.getElementById('sync_server_port').value;

    fetch('/api/settings', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            
        },
        body: JSON.stringify({
            LLM: {
                SERVER_IP: llm_server_ip,
                SERVER_PORT: llm_server_port,
                EMBEDDING_MODEL: llm_embedding_model,
                API_PORT: llm_api_port,
                MODEL_NAME: llm_model_name,
                API_KEY: llm_api_key
            },
            RAG: {
                PERSIS_PATH: rag_persist_path
            },
            FILE_SYSTEM: {
                UPLOAD_FOLDER: fs_persist_path,
                CHROMA_DB: fs_chroma_db,
                JWT_SECRET_KEY: fs_jwt_secret_key
            },
            AUDIO: {
                SAMPLE_RATE: audio_sample_rate,
                CHANNELS: audio_channels,
                CHUNK_SIZE: audio_chunk_size,
                SILENCE_THRESHOLD: audio_silence_threshold,
                SILENCE_DURATION: audio_silence_duration,
                BUFFER_DURATION: audio_buffer_duration,
                SERVER_IP: audio_server_ip,
                SERVER_PORT: audio_server_port,
                WAKE_WORDS: audio_wake_words,
                SLEEP_WORDS: audio_sleep_words
            },
            FISHSPEECH: {
                DEFAULT_API_TOKEN: default_api_token,
                DEFAULT_MODEL_ID: default_model_id,
                DEFAULT_AUDIO_FORMAT: default_audio_format,
                DEFAULT_TTS_VERSION: default_tts_version,
                FISH_SPEECH_URL: default_speech_url
            },
            SYNCSERVER: {
                SERVER_IP: sync_server_ip,
                SERVER_PORT: sync_server_port
            }
        })
    })
    .then(response => response.json())
    .then(data => {
        modal.style.display = 'none';
        alert(data.message || '设置已保存');
    })
    .catch(error => console.error('保存设置失败:', error));
}
